package com.swjd.sort;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

//接收消息
public class Consumer {
    public static void main(String[] args) throws MQClientException {
        //接收消息的对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group1");
        //接收的服务器地址
        consumer.setNamesrvAddr("localhost:9876");
        //设置接收的消息
        consumer.subscribe("topic11","*");
        //使用单线程的模式从消息队列中取数据，一个线程绑定一个消息队列
        consumer.registerMessageListener(new MessageListenerOrderly() {
        //使用MessageListenerOrderly接口后，对消息队列的处理由一个消息队列多个线程服务，转化为一个消息队列一个线程服务
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list,
                                                       ConsumeOrderlyContext consumeOrderlyContext) {
                for (MessageExt msg : list) {
                    System.out.println(Thread.currentThread().getName()+"。消息："
                            + new String(msg.getBody())+"。queueId:"+msg.getQueueId());
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        //启动服务
        consumer.start();
        System.out.println("接收服务已开启");
    }
}
